package com.zjut.SimpleRPC.codec;


import com.zjut.SimpleRPC.codec.serialize.Serializer;
import com.zjut.SimpleRPC.codec.serialize.SerializerByJson;
import com.zjut.SimpleRPC.codec.serialize.SerializerByProtoStuff;

import java.io.IOException;

/**
 * Created by Ryan on 2016/11/24.
 */
public class NettyCodecAdapter implements Codec {


    private Serializer serializer;


    public NettyCodecAdapter setSerializer(Serializer serializer) {
        this.serializer = serializer;
        return this;
    }

    private NettyCodecAdapter() {
    }

    @Override
    public byte[] encode(Object obj) throws IOException {
        return serializer == null ? SerializerByProtoStuff.getInstance().serialize(obj) : serializer.serialize(obj);
    }

    @Override
    public <T> T decode(byte[] bytes, Class<T> clazz) throws IOException {
        return serializer == null ? SerializerByProtoStuff.getInstance().deserialize(bytes, clazz) : serializer.deserialize(bytes, clazz);
    }

    public static NettyCodecAdapter getInstance() {
        return Instance.getInstance();
    }

    static class Instance {
        private static NettyCodecAdapter nettyCodecAdapter = new NettyCodecAdapter();

        public static NettyCodecAdapter getInstance() {
            return nettyCodecAdapter;
        }
    }
}
